package org.yray.bytebuddy;

import net.bytebuddy.ByteBuddy;
import net.bytebuddy.agent.ByteBuddyAgent;
import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.dynamic.loading.ClassReloadingStrategy;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.matcher.ElementMatchers;
import net.bytebuddy.utility.JavaModule;
import org.yray.javaagent.MyTransformer;

import java.lang.instrument.Instrumentation;
import java.lang.instrument.UnmodifiableClassException;
import java.security.ProtectionDomain;

public class PreMainAgent {
    public static void premain(String agentArgs, Instrumentation ins) {

        System.out.println("MainAgent:" + agentArgs);
        AgentBuilder.Transformer transformer=new AgentBuilder.Transformer() {
            @Override
            public DynamicType.Builder<?> transform(DynamicType.Builder<?> builder, TypeDescription typeDescription, ClassLoader classLoader, JavaModule javaModule) {
                System.out.println("transform:" + agentArgs);
                return builder
                        .method(ElementMatchers.named("list"))
                        .intercept(MethodDelegation.to(MyServiceInterceptor.class));
            }

        };
        AgentBuilder agentBuilder =  new AgentBuilder.Default().with(new MyListener());
        agentBuilder.type(ElementMatchers.nameStartsWith("org.yray.javaagent.exec"))
                .transform(transformer).installOn(ins);
        System.out.println("MainAgent,begin foreach:" + agentArgs);
    }
}
